package models

import (
	"github.com/unknwon/com"
)

type ExaCustomer struct {
	ModelBase
	CustomerName       string  `json:"customerName" form:"customerName" gorm:"comment:客户名"`                // 客户名
	CustomerPhoneData  string  `json:"customerPhoneData" form:"customerPhoneData" gorm:"comment:客户手机号"`    // 客户手机号
	SysUserID          uint    `json:"sysUserId" form:"sysUserId" gorm:"comment:管理ID"`                     // 管理ID
	SysUserAuthorityID string  `json:"sysUserAuthorityID" form:"sysUserAuthorityID" gorm:"comment:管理角色ID"` // 管理角色ID
	SysUser            SysUser `json:"sysUser" form:"sysUser" gorm:"comment:管理详情"`                         // 管理详情
}

//@function: CreateExaCustomer
//@description: 创建客户
//@param: e model.ExaCustomer
//@return: err error

func CreateExaCustomer(e ExaCustomer) (err error) {
	err = db.Create(&e).Error
	return err
}

//@function: UpdateExaCustomer
//@description: 更新客户
//@param: e *model.ExaCustomer
//@return: err error

func UpdateExaCustomer(e *ExaCustomer) (err error) {
	err = db.Save(e).Error
	return err
}

//@function: DeleteFileChunk
//@description: 删除客户
//@param: e model.ExaCustomer
//@return: err error

func DeleteExaCustomer(id int) (err error) {
	var customer ExaCustomer
	return db.Where("`id` = ?", id).Delete(&customer).Error
}

//@function: GetExaCustomer
//@description: 获取客户信息
//@param: id uint
//@return: err error, customer model.ExaCustomer

func GetExaCustomer(id uint) (err error, customer ExaCustomer) {
	err = db.Where("id = ?", id).First(&customer).Error
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetCustomerInfoList
//@description: 分页获取客户列表
//@param: sysUserAuthorityID string, info request.PageInfo
//@return: err error, list interface{}, total int64

func GetCustomerInfoList(sysUserAuthorityID uint, page, pageSize int) (err error, list interface{}, total int64) {
	limit := pageSize
	offset := pageSize * (page - 1)
	adb := db.Model(&ExaCustomer{})
	var a SysAuthority
	a.AuthorityId = sysUserAuthorityID
	id := com.StrTo(sysUserAuthorityID).MustInt64()
	err, auth := GetAuthorityInfo(id)
	var dataId []uint
	for _, v := range auth.DataAuthorityId {
		dataId = append(dataId, v.AuthorityId)
	}
	var CustomerList []ExaCustomer
	err = adb.Where("sys_user_authority_id in ?", dataId).Count(&total).Error
	if err != nil {
		return err, CustomerList, total
	} else {
		err = adb.Limit(limit).Offset(offset).Preload("SysUser").Where("sys_user_authority_id in ?", dataId).Find(&CustomerList).Error
	}
	return err, CustomerList, total
}
